<?php
namespace haibao\classlibrary\cms\common;

use haibao\cms\data\FeaturePublish;

use \haibao\frame\http\Request;
use haibao\cms\model\data\FeaturePublish as FeatureModel;
use haibao\frame\data\query\Condition;
use \haibao\classlibrary\cms\common\File as FileCommon;
use haibao\frame\http\Template;
use haibao\cms\model\filter\FeatureIni as FeatureIniFilter;
use haibao\cms\model\filter\FeatureParam as FeatureParamFilter;
use haibao\cms\business\FeaturePublish as FeaturePublishBusiness;
use haibao\cms\model\data\FeatureIni as FeatureIniModel;
use haibao\cms\model\data\FeatureParam as FeatureParamModel;
use haibao\cms\model\data\FeatureIni;

class Feature{
	const FEATURE_PATH = 'feature';
	const FEATURE_TMP_PATH = 'tmp';
	const FEATURE_COMBINE_PATH = 'static';
	const FEATURE_BASE_URL = 'featureview';
	const FEATURE_MAIN_HTML_NAME = 'index.html';
	const FEATURE_INI_NAME = 'settings.ini';
	const FEATURE_JS_CONFIG_NAME = 'config.js';
	const FEATURE_IMG_DIR = 'images';
	const FEATURE_TEMPLATE_NAME = 'feature_template.zip';
	const FEATURE_HTML_NEW_LINE = '{{newline}}';
	const FEATURE_VOTE_JS_PATH = '/resource/js/vote.js';
	const FEATURE_WEIXIN_SHARE_JS_PATH = '/resource/js/weixinshare.js';
	const FEATURE_DYNAMIC_JS_PATH = '/resource/js/dynamic.js';
	const FEATURE_OLD_IMG_PATH = '/feature_img';
	const FEATURE_OLD_IMG_BASE_URL = 'http://cdn6.hbimg.cn/store/topicpic/';
	const FEATURE_OLD_FEATURE_PATH = '/feature_static';
	const FEATURE_VOTE_JS_NAME = 'vote.js';
	const FEATURE_WEIXIN_SHARE_JS_NAME = 'weixinshare.js';
	const FEATURE_DYNAMIC_JS_NAME = 'dynamic.js';
	const FEATURE_UPLOAD_BASE_URL = 'www.haibao.com/features/';
	const FEATURE_UPLOAD_BASE_URL_H5 = 'm.haibao.com/features/';
	const FEATURE_SVN_URL = 'svn://10.15.203.49/project/fd.haibao.cn/trunk/feature/';
	const FEATURE_URL_NORMAL = 'http://www.haibao.com/features/';
	const FEATURE_URL_H5 = 'http://m.haibao.com/features/';
	const FEATURE_CSS_HAIBAO_HEADER = '<link rel="stylesheet" type="text/css" href="{{staticHost}}/feature/pcheader/css/hbreset:{{version}}.css">';
	const FEATURE_JS_HAIBAO_HEADER = '<script type="text/javascript" src="{{staticHost}}/feature/pcheader/js/common:{{version}}.js"></script>';
	const FEATURE_CSS_HAIBAO_HEADER_NEW = '<link rel="stylesheet" type="text/css" href="{{staticHost}}/feature/pcheader/css/hbresetnew:{{version}}.css">';
	const FEATURE_JS_HAIBAO_HEADER_NEW = '<script type="text/javascript" src="{{staticHost}}/feature/pcheader/js/commonnew:{{version}}.js"></script>';
	const FEATURE_JS_HAIBAO_HEADER_SCROLL = '<script type="text/javascript" src="{{staticHost}}/js/plugin/jquery.mCustomScrollbar.min:{{version}}.js"></script>';
	
	const FEATURE_INI_DYNAMIC_ITEM = 'dynamic_item';
	const FEATURE_INI_DYNAMIC = 'dynamic';
	const FEATURE_INI_DYNAMIC_GROUP = 'dynamic_group';
	const FEATURE_DYNAMIC_ITEM_TYPE_IMG = 'img';
	const FEATURE_DYNAMIC_ITEM_TYPE_TEXT = 'text';
	const FEATURE_DYNAMIC_ITEM_TYPE_INPUT = 'input';
	
	const AJAX_URL_WEIXINSHARE_DEV = '/ajax/feature:getWeixinSdk.json';
	const AJAX_URL_WEIXINSHARE = '/html/2014WAP/jssdk.php';
	const AJAX_URL_DYNAMIC_DEV = '/ajax/feature:getDynamicList.json';
	const AJAX_URL_DYNAMIC = '/index.php?c=ajax&a=getDynamicList';
	const AJAX_URL_VOTE_DEV = '/ajax/feature:vote.json';
	const AJAX_URL_UN_VOTE_DEV = '/ajax/feature:unVote.json';
	const AJAX_URL_VOTE_GET_COUNT_DEV = '/ajax/feature:getVoteCount.json';
	const AJAX_URL_VOTE_GET_ALL_DATA_DEV = '/ajax/feature:getAllVoteData.json';
	const AJAX_URL_VOTE = '/index.php?c=ajax&a=featureVote';
	const AJAX_URL_UN_VOTE = '/index.php?c=ajax&a=unFeatureVote';
	const AJAX_URL_VOTE_GET_COUNT = '/index.php?c=ajax&a=getFeatureVoteCount';
	const AJAX_URL_VOTE_GET_ALL_DATA = '/index.php?c=ajax&a=getAllFeatureVoteData';
	const AJAX_URL_RECORD_DEV = '/ajax/feature:addFeatureRecorde.json';
	const AJAX_URL_RECORD = '/index.php?c=ajax&a=addFeatureRecord';
	const AJAX_URL_IMG_UPLOAD_DEV = '/ajax/feature:uploadImg.json';
	const AJAX_URL_IMG_UPLOAD = '/index.php?c=ajax&a=uploadFeatureImg';
	const AJAX_URL_IMG_SET_BORDER_DEV = '/ajax/feature:setImgBorder.json';
	const AJAX_URL_IMG_SET_BORDER  = '/index.php?c=ajax&a=setFeatureImgBorder';
	const AJAX_URL_IMG_SHOW_BY_ID_DEV = '/ajax/feature:showImgById.json';
	const AJAX_URL_IMG_SHOW_BY_ID = '/index.php?c=ajax&a=showFeatureImgById';
	const AJAX_URL_IMG_GET_IMG_LIST_DEV = '/ajax/feature:getImgList.json';
	const AJAX_URL_IMG_GET_IMG_LIST = '/index.php?c=ajax&a=getFeatureImgList';
	const AJAX_URL_ADD_PV = '/ajax/feature:addpv.json';
	const AJAX_URL_SHARE_COUNT = '/ajax/feature:sharecount.json';
	
	const SCRIPT_URL_VOTE = '{{staticHost}}/feature/feature-vote:{{version}}.js';
	const SCRIPT_URL_WEIXINSHARE = '{{staticHost}}/feature/feature-weixinshare:{{version}}.js';
	const SCRIPT_URL_DYNAMIC = '{{staticHost}}/feature/feature-dynamic:{{version}}.js';
	const SCRIPT_URL_RECORD = '{{staticHost}}/feature/feature-record:{{version}}.js';
	const SCRIPT_URL_QRCODE = '{{staticHost}}/feature/jquery.qrcode:{{version}}.js';
	const SCRIPT_URL_SHARE = '{{staticHost}}/feature/pcheader/js/share:{{version}}.js';
	const SCRIPT_URL_MESSAGE_BOX = '{{staticHost}}/js/plugin/haibao.messagebox:{{version}}.js';
	const SCRIPT_URL_HREF_RECORD = '{{staticHost}}/feature/hrefrecord:{{version}}.js';
	
	const SCRIPT_URL_LOGIN = '{{staticHost}}/js/jquery.mask,share,checklogin:{{version}}.js';
	const SCRIPT_URL_COMMENT = '{{staticHost}}/js/plugin/haibao.comment:{{version}}.js';
	const SCRIPT_URL_TAB = '{{staticHost}}/js/plugin/haibao.tab:{{version}}.js';
	const SCRIPT_URL_SCROLLBAR = '{{staticHost}}/js/plugin/jquery.mCustomScrollbar.min:{{version}}.js';
	
	const CSS_URL_HB_COMMON = '{{staticHost}}/css/hb_common:{{version}}.css';
	
	const FEATURE_FILE_TYPE_IMAGE = 1;
	const FEATURE_FILE_TYPE_AUDIO = 2;
	const FEATURE_FILE_TYPE_VIDEO = 3;
	const FEATURE_FILE_TYPE_ZIP = 4;
	
	private static $feature = null;
	private static $featureId = null;
	private static $featureDefineId = null;
	private static $dynamicData = null;
	private static $dynamicJudgeMatched = false;
	private static $iniSysKeys = array(
		'system'=>'系统参数',
		self::FEATURE_INI_DYNAMIC => '动态数据',
	);
	
	private static $iniSysDesc = array(
		'title'=>'标题',
		'description'=>'页面描述',
		'keywords'=>'关键词',
		'vote'=>'投票程序',
		'haibaoHeader'=>'海报头文件',
		'haibaoBottom'=>'海报尾文件',
		'goTop'=>'返回顶部按钮',
		'pcShare'=>'pc分享',
		'weixinShare'=>'微信分享',
		'dynamic'=>'动态数据'
	);
	
	private static $serverNames = array('features_www');
	private static $mobileServerNames = array('features_mobile');
	private static $ignoreInIKeys = array(self::FEATURE_INI_DYNAMIC_ITEM);
	public static $featureFilePaths = array('featurefiles1','featurefiles2');
	public static $featureSvn = 'feature_svn';
	public static $featureFileDirNames = array(
		self::FEATURE_FILE_TYPE_IMAGE => 'image',
		self::FEATURE_FILE_TYPE_AUDIO => 'audio',
		self::FEATURE_FILE_TYPE_VIDEO => 'video',
		self::FEATURE_FILE_TYPE_ZIP	=> 'zip'
	);
	
	private static $cmsDomain = '';
	private static $cmsPath = '';
	
	public static function setCmsDomainAndPath($domain,$path){
		self::$cmsDomain = $domain;
		self::$cmsPath = $path;
	}
	
	public static function getCmsDomain(){
		return self::$cmsDomain ? self::$cmsDomain : \haibao\frame\http\HttpEnvironment::domain();
	}
	
	public static function getCmsPath(){
		return self::$cmsPath ? self::$cmsPath : \haibao\frame\http\HttpEnvironment::path();
	}
	
	public static function checkoutSvn($svnUrl,$dir){
		$checked = true;
		
		try{
			$fullSvnPath = self::getCmsPath().DIRECTORY_SEPARATOR.self::$featureSvn.DIRECTORY_SEPARATOR.$svnUrl;
			FileCommon::copyResource($fullSvnPath,$dir);
		}catch (\Exception $e){
			$checked = false;
		}
		
		return $checked;
	}
	
	public static function uploadFeatureChannel($model,$oldFeatureId){
		$combinePath = self::combineFeature($model,$oldFeatureId,true);
		if ($combinePath){
			if ($model->IsH5){
				$arr = explode(self::FEATURE_UPLOAD_BASE_URL_H5,$model->Url);
			}
			else{
				$arr = explode(self::FEATURE_UPLOAD_BASE_URL,$model->Url);
			}
			
			$toUrl = rtrim(array_pop($arr).'/');
			$serverNames = self::getServerNames($model->IsH5);
			
			foreach ($serverNames as $serverName){
				$toPath = self::getOldFeaturePath().'/'.$serverName.'/'.$toUrl.'/channel';
				if (file_exists($toPath)){			
					FileCommon::removeResource($toPath,false);
				}
				
				FileCommon::copyResource($combinePath,$toPath);
			}
		}
	}
	
	public static function formatFeatureCssData($featureId,&$content){
		$feature = \haibao\cms\business\FeaturePublish::getFeatureById($featureId);
		$content = self::replaceStaticUrl($content,false);
		$paramFilter = new FeatureParamFilter();
		$paramFilter->where(FeatureParamFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,$feature->FeatureDefineId);
		$paramFilter->where(FeatureParamFilter::CONDITION_FIELD_NAME_PARAM_TYPE,Condition::CONDITION_EQUAL,FeatureParamModel::PARAM_TYPE_CSS);
		if ($models = FeaturePublishBusiness::getAllParamList($paramFilter)){
			//html,替换{{$name}}标记
			$content = preg_replace_callback('/{{(.*?)}}/is',function ($matches) use ($models) {
				if ($matches){
					$name = $matches[1];
					$replace = '';
					foreach ($models as $model){
						if (strtolower($model->Code) == strtolower($name)){
							$replace = nl2br($model->Value);
						}
					}
			
					return $replace;
				}
			},$content);
		}
	}
	
	public static function getItemType($type){
		$itemType = null;
		$type = strtolower($type);
		switch ($type){
			case 'img':
				$itemType = \haibao\cms\model\data\FeatureGroupDefineItem::ITEM_TYPE_IMG;
				break;
			case 'text':
			case 'textarea':
				$itemType = \haibao\cms\model\data\FeatureGroupDefineItem::ITEM_TYPE_TEXT;
				break;
			case 'time':
				$itemType = \haibao\cms\model\data\FeatureGroupDefineItem::ITEM_TYPE_TIME;
				break;
			default:
				$itemType = \haibao\cms\model\data\FeatureGroupDefineItem::ITEM_TYPE_INPUT;
				break;
		}
		
		return $itemType;
	}
	
	public static function saveOldFeatureImage($imgName){
		$picName = '';
		if ($imgName){
			$arr = array(
					'tmp_name'=>$imgName,
					'name'=>$imgName
			);
			$imgInfo = \haibao\cms\business\ImageLibrary::saveUpload($arr, \haibao\cms\model\data\ImageLibrary::UPLOAD_SOURCE_FEATURE,false);
			$common = new \haibao\classlibrary\cms\common\Article();
			$picName = $common->replaceImageLink($imgInfo['imageUrl'],0,0,100,0);
		}
		
		return $picName;
	}
	
	public static function saveFeatureFile($filePath,$type){
		$name = '';
		if (file_exists($filePath)){
			$fileName = explode('/',$filePath);
			$fileName = date('Ymd').'/'.date('His').'.'.mt_rand(100,900).'/'.array_pop($fileName);
			foreach (self::$featureFilePaths as $pathName){
				$dirName = self::getCmsPath().'/'.$pathName.'/'.self::$featureFileDirNames[$type];
				$fullFilePath = $dirName.'/'.$fileName;
				self::mkFolder(dirname($fullFilePath));
				FileCommon::filePutContents($fullFilePath);
				copy($filePath, $fullFilePath);
				$name = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN).'/feature/files/'.self::$featureFileDirNames[$type].'/'.$fileName;
			}
		}
		
		return $name;
	}
	
	public static function getFeatureZipByFileName($fileName){
		$content = '';
		$randPath = self::$featureFilePaths[array_rand(self::$featureFilePaths)];
		$filePath = self::getCmsPath().DIRECTORY_SEPARATOR.$randPath;
		$filePath .= DIRECTORY_SEPARATOR.self::$featureFileDirNames[self::FEATURE_FILE_TYPE_ZIP].DIRECTORY_SEPARATOR.$fileName;
		
		if (file_exists($filePath)){
			$content = file_get_contents($filePath);
		}
		
		return $content;
	}
	
	public static function saveFeatureZipFile($fileName,$fullPath='',$copyFileName=''){
		if ($copyFileName){
			$randPath = self::$featureFilePaths[array_rand(self::$featureFilePaths)];
			$fullPath = self::getCmsPath().DIRECTORY_SEPARATOR.$randPath.DIRECTORY_SEPARATOR;
			$fullPath .= self::$featureFileDirNames[self::FEATURE_FILE_TYPE_ZIP].DIRECTORY_SEPARATOR.$copyFileName;
		}
		if (file_exists($fullPath)){
			$filePath = DIRECTORY_SEPARATOR.self::$featureFileDirNames[self::FEATURE_FILE_TYPE_ZIP].DIRECTORY_SEPARATOR.$fileName;
			foreach (self::$featureFilePaths as $pathName){
				$toPath = self::getCmsPath().DIRECTORY_SEPARATOR.$pathName.$filePath;
				self::mkFolder(dirname($toPath));
				FileCommon::filePutContents($toPath);
				copy($fullPath,$toPath);
			}
		}
	}
	
	public static function mkFolder($folder){
		if (!file_exists($folder)){
			self::mkFolder(dirname($folder));
			mkdir($folder,0777);
		}
	}
	
	public static function getImgCdnUrl($picName){
		$baseName = baseName($picName);
		//$serverNumber = intval($baseName)%6;
		$hash = crc32($baseName) >> 16 & 0xffff;
		$cdnHostArr = array(
					'http://cdn0.hbimg.cn',
					'http://cdn2.hbimg.cn',
					'http://cdn4.hbimg.cn',
					'http://cdn6.hbimg.cn',
			);
		$serverNumber = sprintf('%01s',$hash % count($cdnHostArr));
		
		return $cdnHostArr[$serverNumber].'/store/topicpic/special/'.$baseName;
	}
	
	public static function getDynamic($dirPath,$groupCode){
		$data = null;
		$iniFilePath = self::getFeatureFilePath().'/'.$dirPath.'/'.self::FEATURE_INI_NAME;
		if (file_exists($iniFilePath)){
			$iniData = parse_ini_file($iniFilePath,true);
			$dynamicKey = self::FEATURE_INI_DYNAMIC_ITEM.'_'.$groupCode;
			if (isset($iniData[$dynamicKey])){
				$data = $iniData[$dynamicKey];
			}
		}
		
		return $data;
	}
	
	public static function checkIniKey($key){
		$checked = true;
		foreach (self::$ignoreInIKeys as $pattern){
			if (stripos($key,$pattern) !== false){
				$checked = false;	
			}
		}
		
		return $checked;
	}
	
	public static function extractFeatureZip($zipName,$zipContent,$featureName){
		$zipFileName = self::getFeatureTmpPath().DIRECTORY_SEPARATOR.$zipName;
		FileCommon::filePutContents($zipFileName,$zipContent);
	
		$zip = new \ZipArchive();
		$zip->open($zipFileName);
		$filePath = self::getFeatureFilePath().'/'.md5($featureName);
		
		if (file_exists($filePath)){
			FileCommon::removeResource($filePath,false);
		}
		$zip->extractTo($filePath);
		$zip->close();
		
		return $filePath;
	}
	
	public static function getFeatureUrlPrefix($isH5){
		if ($isH5){
			return self::FEATURE_URL_H5;
		}
		else{
			return self::FEATURE_URL_NORMAL;
		}
	}
	
	public static function getFeatureUrl($url,$isH5){
		$str = '';
		if ($url){
			if ($isH5){
				$str = self::FEATURE_URL_H5.rtrim($url,'/').'/';
			}
			else{
				$str = self::FEATURE_URL_NORMAL.rtrim($url,'/').'/';
			}
		}
		
		return $str;
	}
	
	public static function getRealFeatureUrl($url,$isH5){
		$realUrl = '';
		if ($url){
			$pattern = '';
			if ($isH5){
				$pattern = self::FEATURE_URL_H5;
			}
			else{
				$pattern = self::FEATURE_URL_NORMAL;
			}
			
			$arr = explode($pattern,$url);
			$realUrl = array_pop($arr);
			$realUrl = rtrim($realUrl,'/');
		}
		
		return $realUrl;
	}
	
	public static function getFullSvnUrl($url){
		return self::FEATURE_SVN_URL.$url;
	}
	
	public static function getIniSystemDesc($keyName){
		if (in_array($keyName,array_keys(self::$iniSysDesc))){
			$keyName = self::$iniSysDesc[$keyName];
		}
		
		return $keyName;
	}
	
	public static function isLocal(){
		$isLocal = false;
		if (stripos(self::getCmsDomain(),'local') !== false){
			$isLocal = true;
		}
		
		return $isLocal;
	}
	
	public static function isFormal(){
		$isFormal = true;
		if (
				stripos(self::getCmsDomain(),'local') !== false
			||	stripos(self::getCmsDomain(),'dev') !== false
		){
			$isFormal = false;
		}
	
		return $isFormal;
	}
	
	public static function getOldImgPath(){
		return self::getCmsPath().self::FEATURE_OLD_IMG_PATH;
	}
	
	public static function getOldFeaturePath(){
		return self::getCmsPath().self::FEATURE_OLD_FEATURE_PATH;
	}
	
	public static function formatDateTime($dateTime){
		$date = null;
		if ($dateTime instanceof \DateTime && $dateTime->format('Y') != '-0001'){
			$date = $dateTime;
		}
		
		return $date;
	}
	
	public static function formatTime($dateTime,$formatStr = 'Y-m-d H:i:s'){
		$date = '';
		if ($dateTime instanceof \DateTime && $dateTime->format('Y') != '-0001'){
			$date = date($formatStr);
		}
		
		return $date;
	}
	
	public static function getFeatureClasses(){
		return array(
			FeatureModel::CLASS_DESIGNER=>'设计师',
			FeatureModel::CLASS_BRAND_TOP=>'品牌高层',
			FeatureModel::CLASS_OTHER=>'其他',
			FeatureModel::CLASS_FASHION=>'潮流',
			FeatureModel::CLASS_PAINT=>'美妆',
			FeatureModel::CLASS_STAR=>'明星',
			FeatureModel::CLASS_FASHION_WEEK=>'时装周',
			FeatureModel::CLASS_BRAND=>'品牌',
			FeatureModel::CLASS_ZHIBO=>'秀场直播',
			FeatureModel::CLASS_BRAND_DINGZHI=>'品牌定制'
		);
	}
	
	public static function getFeatureColumns(){
		$columns = array(
			FeatureModel::COLUMN_EVALUTE=>'海报口碑测评(非视频)',
			FeatureModel::COLUMN_FASHION_ARCHIVE=>'时装档案(非视频)',
			FeatureModel::COLUMN_PERFECT_ADVICE=>'完美主张(非视频)',
			FeatureModel::COLUMN_NEW_PRODUCT=>'top新品见报(非视频)'
		);
		
		$filter = new \haibao\cms\model\filter\VideoCategory();
		$filter->where(\haibao\cms\model\filter\VideoCategory::CONDITION_FIELD_NAME_PARENTID,Condition::CONDITION_EQUAL,2);
		$filter->where(\haibao\cms\model\filter\VideoCategory::CONDITION_FIELD_NAME_STATUS,Condition::CONDITION_EQUAL,1);
		$filter->where(\haibao\cms\model\filter\VideoCategory::CONDITION_FIELD_NAME_ID,Condition::CONDITION_NOTEQUAL,34);
		$filter->order(\haibao\cms\model\filter\VideoCategory::CONDITION_FIELD_NAME_PARENTID);
		$videoCates = \haibao\cms\business\VideoCategory::searchCategories($filter);
		if ($videoCates){
			foreach ($videoCates as $videoCate){
				$columns[$videoCate->Id] = $videoCate->CategoryName;
			}
		}
		
		return $columns;
	}
		
	public static function getIniSysKeys(){
		return array_keys(self::$iniSysKeys);
	}
	
	public static function getIinSysKeyDesc($key){
		$str = '';
		if (isset(self::$iniSysKeys[$key])){
			$str = self::$iniSysKeys[$key];
		}
		
		return $str;
	}
	
	public static function getFeatureTemplatePath(){
		return self::getCmsPath().'/'.self::FEATURE_TEMPLATE_NAME;
	}
	
	public static function getFeatureFilePath(){
		return self::getCmsPath().'/'.self::FEATURE_PATH;
	}
	
	public static function getFeatureTmpPath(){
		return self::getCmsPath().'/'.self::FEATURE_PATH.'/'.self::FEATURE_TMP_PATH;
	}
	
	public static function getFeatureCombinePath(){
		return self::getCmsPath().'/'.self::FEATURE_PATH.'/'.self::FEATURE_COMBINE_PATH;
	}
	
	/**
	 * 编译并上传专题
	 * @param obj $featureModel
	 * @param int $oldFeatureId
	 */
	public static function combineFeature($featureModel,$oldFeatureId,$isChannel = false){
		$combinePath = '';
		$fileDir = self::getFeatureFilePath().'/'.md5($featureModel->FeatureDefine->FeatureName.$featureModel->IsH5);
		
		if (file_exists($fileDir)){
			//复制到编译目录
			$combinePath = self::getFeatureCombinePath().'/'.md5($featureModel->FeatureDefine->FeatureName.$featureModel->IsH5);
			if (file_exists($combinePath)){
				FileCommon::removeResource($combinePath,false);
			}
			FileCommon::copyResource($fileDir, $combinePath);
			
			self::$feature = $featureModel;
			self::$featureDefineId = $featureModel->FeatureDefine->Id;
			$fp = dir($combinePath);
			while ($file = $fp->read()){
				if (!is_dir("$combinePath/$file") && preg_match('/index\d*.html/i',$file)){
					$mainFilePath = $combinePath.'/'.$file;
					$html = self::compileFeature($mainFilePath,$featureModel->Id,$oldFeatureId,$featureModel->IsH5,true,$isChannel);
					file_put_contents($mainFilePath,$html);
				}
			}
		}
		
		return $combinePath;
	}
	
	public static function getServerNames($isH5){
		if ($isH5){
			return self::$mobileServerNames;
		}
		else{
			return self::$serverNames;
		}
	}
	
	public static function uploadFeature($url,$combineDir,$isH5){
		if ($isH5){
			$arr = explode(self::FEATURE_UPLOAD_BASE_URL_H5,$url);
		}
		else{
			$arr = explode(self::FEATURE_UPLOAD_BASE_URL,$url);
		}
		
		$toUrl = rtrim(array_pop($arr).'/');
		$serverNames = self::getServerNames($isH5);
		
		foreach ($serverNames as $serverName){
			$toPath = self::getOldFeaturePath().'/'.$serverName.'/'.$toUrl;
			if (file_exists($toPath)){			
				FileCommon::removeResource($toPath,false);
			}
			
			FileCommon::copyResource($combineDir,$toPath);
		}
	}
	
	public static function ftpCopy($conn,$src,$dst){
		if (false !== ($dir = opendir($src))){
			if (!file_exists($dst)){
				ftp_mkdir($conn,$dst);
			}
			while(false !== ( $file = readdir($dir)) ) {
				if (( $file != '.' ) && ( $file != '..' )) {
					if ( is_dir($src . '/' . $file) ) {
						self::ftpCopy($conn,$src . '/' . $file,$dst . '/' . $file);
					}
					else {
						ftp_put($conn,$dst.'/'.$file,$src.'/'.$file,FTP_ASCII);
					}
				}
			}
			closedir($dir);
		}else if (is_file($src)){
			ftp_put($conn,$dst,$src,FTP_ASCII);
		}
	}
	
	/**
	 * 编译专题，返回主文件html
	 * @param string $featurePath
	 */
	public static function compileFeature($featurePath,$featureId,$oldFeatureId = null,$isH5 = false,$isUpload = false,$isChannel = false){
		$html = file_get_contents($featurePath);
		
		$dirPath = dirname($featurePath);
		self::formatFeature($html,$featureId,$oldFeatureId,$dirPath,$isH5,$isUpload,$isChannel);

		//包含点击统计文件
		if ($isUpload && !$isChannel){
			$template = new Template();
			$template->assign('isH5',$isH5);
			$template->assign('isUpload',$isUpload);
			$insert = $template->getHtml('/feature/bottomjs.htm');
			self::insertIntoHtmlBottom($html, $insert);
		}
		
		if ($isUpload && $isChannel){
			$template = new Template();
			$insert = $template->getHtml('/feature/channeljs.html');
			self::insertIntoHeaderBottom($html, $insert);
		}
		
		if ($isUpload){
			$articleCommon = new \haibao\classlibrary\cms\common\Article();
			$html = $articleCommon->replaceCDNLink($html);
		}
		
		return $html;
	}
	
	public static function includeFeatureTop(&$html,$headerType){
		$template = new Template();
		$template->assign('headerType',$headerType);
		$insert = $template->getHtml('/feature/top.htm');
		self::insertIntoHtmlTop($html, $insert);
	}
	
	public static function includeFeatureBottom(&$html,$iniModel,$isH5 = false,$isChannel = false){
		$template = new Template();
		
		if ($iniModel->HaibaoBottom == FeatureIniModel::STATUS_ENABLE){
			$template->assign('haibaoBottom',true);
		}
		if ($iniModel->PcShare == FeatureIniModel::STATUS_ENABLE){
			$template->assign('pcShare',true);
		}
		if ($iniModel->GoTop == FeatureIniModel::STATUS_ENABLE){
			$template->assign('goTop',true);
		}
		$template->assign('isChannel',$isChannel);
		$template->assign('year',date('Y'));
		$template->assign('isH5',$isH5);
		$insert = $template->getHtml('/feature/newbottom.html');
		
		self::insertIntoHtmlBottom($html, $insert);
	}
	
	public static function checkMainFileNameFromZip($fileName){
		$checked = false;
		$res = zip_open($fileName);
		while ($id = zip_read($res)){
			if (zip_entry_open($res, $id)){
				$name = zip_entry_name($id);
				//只检测第一级目录的文件
				if (false === stripos($name,'/')){
					if ($name == self::FEATURE_MAIN_HTML_NAME){
						$checked = true;
					}
				}
				zip_entry_close($id);
			}
		}
	
		return $checked;
	}
	
	public static function checkMainFileNameFromDir($fileName){
		$checked = false;
		if (is_dir($fileName)){
			$dir = opendir($fileName);
			while(false !== ( $file = readdir($dir)) ) {
				if (substr($file,0,1) != '.'){
					if ($file == self::FEATURE_MAIN_HTML_NAME){
						$checked = true;
					}
				}
			}
		}
	
		return $checked;
	}
	
	public static function insertIntoHtmlTop(&$html,$insert){
		$pos = mb_stripos($html,'<body>',0,'utf-8');
		if ($pos !== false){
			$length = mb_strlen($html,'utf-8');
			$pos += mb_strlen('<body>','utf-8');
			$left = mb_substr($html,0,$pos,'utf-8');
			$right = mb_substr($html,$pos,$length-$pos,'utf-8');
			$html = $left.$insert.PHP_EOL.$right;
		}
	}
	
	public static function insertIntoHtmlBottom(&$html,$insert){
		$pos = mb_stripos($html,'</body>',0,'utf-8');
		if ($pos !== false){
			$length = mb_strlen($html,'utf-8');
			$left = mb_substr($html,0,$pos,'utf-8');
			$right = mb_substr($html,$pos,$length-$pos,'utf-8');
			$html = $left.$insert.PHP_EOL.$right;
		}
	}
	
	public static function insertIntoHeaderBottom(&$html,$insert){
		$pos = mb_stripos($html,'</head>',0,'utf-8');
		if ($pos !== false){
			$length = mb_strlen($html,'utf-8');
			$left = mb_substr($html,0,$pos,'utf-8');
			$right = mb_substr($html,$pos,$length-$pos,'utf-8');
			$html = $left.$insert.PHP_EOL.$right;
		}
	}
	
	public static function insertIntoHeaderTop(&$html,$insert){
		$pos = mb_stripos($html,'<head>',0,'utf-8');
		if ($pos !== false){
			$length = mb_strlen($html,'utf-8');
			$pos += mb_strlen('<head>','utf-8');
			$left = mb_substr($html,0,$pos,'utf-8');
			$right = mb_substr($html,$pos,$length-$pos,'utf-8');
			$html = $left.$insert.PHP_EOL.$right;
		}
	}
	
	private static function formatFeatureIniData($featureId,&$html,&$htmlData,$isUpload,&$jsContent,$isH5,$isChannel){
		$iniFilter = new FeatureIniFilter();
		$iniFilter->where(FeatureIniFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,$featureId);
		$models = FeaturePublishBusiness::getAllIni($iniFilter);
		
		//上传图片相关url
		if ($isUpload){
			$jsContent = 'haibao.config.set("uploadImgUrl",'.self::formatJsValue(self::AJAX_URL_IMG_UPLOAD).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("setImgBorderUrl",'.self::formatJsValue(self::AJAX_URL_IMG_SET_BORDER).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("showImgByIdUrl",'.self::formatJsValue(self::AJAX_URL_IMG_SHOW_BY_ID).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("getImgListUrl",'.self::formatJsValue(self::AJAX_URL_IMG_GET_IMG_LIST).');'.PHP_EOL.$jsContent;
		}
		else{
			$jsContent = 'haibao.config.set("uploadImgUrl",'.self::formatJsValue(self::AJAX_URL_IMG_UPLOAD_DEV).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("setImgBorderUrl",'.self::formatJsValue(self::AJAX_URL_IMG_SET_BORDER_DEV).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("showImgByIdUrl",'.self::formatJsValue(self::AJAX_URL_IMG_SHOW_BY_ID_DEV).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("getImgListUrl",'.self::formatJsValue(self::AJAX_URL_IMG_GET_IMG_LIST_DEV).');'.PHP_EOL.$jsContent;
		}
		
		
		if ($iniModel = array_pop($models)){
			$includeHeadJs = false;
			/* $htmlData['title'] = $iniModel->Title;
			$htmlData['description'] = $iniModel->Description;
			$htmlData['keywords'] = $iniModel->Keywords; */
			
			$jsContent = 'haibao.config.set("weixinShareUrl",'.self::formatJsValue($iniModel->WeixinShareUrl).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("weixinShareTitle",'.self::formatJsValue($iniModel->WeixinShareTitle).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("weixinShareDesc",'.self::formatJsValue($iniModel->WeixinShareDesc).');'.PHP_EOL.$jsContent;
			$jsContent = 'haibao.config.set("weixinShareImg",'.self::formatJsValue($iniModel->WeixinShareImg).');'.PHP_EOL.$jsContent;
			
			//投票
			if ($iniModel->Vote == FeatureIniModel::STATUS_ENABLE){
				if ($isUpload){
					$jsContent = 'haibao.config.set("voteUrl",'.self::formatJsValue(self::AJAX_URL_VOTE).');'.PHP_EOL.$jsContent;
					$jsContent = 'haibao.config.set("unVoteUrl",'.self::formatJsValue(self::AJAX_URL_UN_VOTE).');'.PHP_EOL.$jsContent;
					$jsContent = 'haibao.config.set("getVoteCountUrl",'.self::formatJsValue(self::AJAX_URL_VOTE_GET_COUNT).');'.PHP_EOL.$jsContent;
					$jsContent = 'haibao.config.set("getAllVoteData",'.self::formatJsValue(self::AJAX_URL_VOTE_GET_ALL_DATA).');'.PHP_EOL.$jsContent;
				}else{
					$jsContent = 'haibao.config.set("voteUrl",'.self::formatJsValue(self::AJAX_URL_VOTE_DEV).');'.PHP_EOL.$jsContent;
					$jsContent = 'haibao.config.set("unVoteUrl",'.self::formatJsValue(self::AJAX_URL_UN_VOTE_DEV).');'.PHP_EOL.$jsContent;
					$jsContent = 'haibao.config.set("getVoteCountUrl",'.self::formatJsValue(self::AJAX_URL_VOTE_GET_COUNT_DEV).');'.PHP_EOL.$jsContent;
					$jsContent = 'haibao.config.set("getAllVoteData",'.self::formatJsValue(self::AJAX_URL_VOTE_GET_ALL_DATA_DEV).');'.PHP_EOL.$jsContent;
				}

				//self::insertIntoHeaderBottom($html, '<script src="'.self::SCRIPT_URL_VOTE.'" type="text/javascript"></script>');
				$jsContent .= '<script src="'.self::SCRIPT_URL_VOTE.'" type="text/javascript"></script>'.PHP_EOL;
			}
		
			//微信分享
			if ($iniModel->WeixinShare == FeatureIniModel::STATUS_ENABLE){
				if ($isUpload){
					$jsContent = 'haibao.config.set("weixinUrl",'.self::formatJsValue(self::AJAX_URL_WEIXINSHARE).');'.PHP_EOL.$jsContent;
				}else{
					$jsContent = 'haibao.config.set("weixinUrl",'.self::formatJsValue(self::AJAX_URL_WEIXINSHARE_DEV).');'.PHP_EOL.$jsContent;
				}
				//self::insertIntoHeaderBottom($html, '<script src="'.self::SCRIPT_URL_WEIXINSHARE.'" type="text/javascript"></script>');
				$jsContent .= '<script src="'.self::SCRIPT_URL_WEIXINSHARE.'" type="text/javascript"></script>'.PHP_EOL;
			}
		
			//dynamic
			if ($iniModel->Dynamic == FeatureIniModel::STATUS_ENABLE){
				if ($isUpload){
					$jsContent = 'haibao.config.set("dynamicUrl",'.self::formatJsValue(self::AJAX_URL_DYNAMIC).');'.PHP_EOL.$jsContent;
				}else{
					$jsContent = 'haibao.config.set("dynamicUrl",'.self::formatJsValue(self::AJAX_URL_DYNAMIC_DEV).');'.PHP_EOL.$jsContent;
				}
					
				//self::insertIntoHeaderBottom($html, '<script src="'.self::SCRIPT_URL_DYNAMIC.'" type="text/javascript"></script>');
				$jsContent .= '<script src="'.self::SCRIPT_URL_DYNAMIC.'" type="text/javascript"></script>'.PHP_EOL;
			}
		
			if ($iniModel->HaibaoHeader != FeatureIniModel::HEADER_DISABLE || $iniModel->HaibaoBottom != FeatureIniModel::HEADER_DISABLE){
				$jsContent .= self::FEATURE_CSS_HAIBAO_HEADER_NEW.PHP_EOL;
				//$jsContent .= self::FEATURE_JS_HAIBAO_HEADER_NEW.PHP_EOL;
				$jsContent .= self::FEATURE_JS_HAIBAO_HEADER_SCROLL;
				$includeHeadJs = true;
			}
			
			//海报头文件
			if ($iniModel->HaibaoHeader != FeatureIniModel::HEADER_DISABLE && !$isChannel){
				$staticReplaceUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN);
				if ($isUpload){
					$staticReplaceUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DOMAIN);
				}
				$template = new Template();
				$template->assign('staticHost',$staticReplaceUrl);
				$template->assign('version',\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_VERSION));
				$insert = $template->getHtml('/feature/newtop.html');
				self::insertIntoHtmlTop($html, $insert);
			}
			
			//添加记录
			if ($iniModel->Record == FeatureIniModel::STATUS_ENABLE){
				if ($isUpload){
					$jsContent = 'haibao.config.set("recordUrl",'.self::formatJsValue(self::AJAX_URL_RECORD).');'.PHP_EOL.$jsContent;
				}else{
					$jsContent = 'haibao.config.set("recordUrl",'.self::formatJsValue(self::AJAX_URL_RECORD_DEV).');'.PHP_EOL.$jsContent;
				}
				$jsContent .= '<script src="'.self::SCRIPT_URL_RECORD.'" type="text/javascript"></script>'.PHP_EOL;
			}
			
			if ($iniModel->PcShare == FeatureIniModel::STATUS_ENABLE){
				$jsContent .= '<script src="'.self::SCRIPT_URL_QRCODE.'" type="text/javascript"></script>'.PHP_EOL;
				$jsContent .= '<script src="'.self::SCRIPT_URL_LOGIN.'" type="text/javascript"></script>'.PHP_EOL;
				$jsContent .= '<script src="'.self::SCRIPT_URL_SHARE.'" type="text/javascript"></script>'.PHP_EOL;
				$jsContent .= '<script src="'.self::SCRIPT_URL_TAB.'" type="text/javascript"></script>'.PHP_EOL;
				$jsContent .= '<script src="'.self::SCRIPT_URL_COMMENT.'" type="text/javascript"></script>'.PHP_EOL;
				$jsContent .= '<script src="'.self::SCRIPT_URL_SCROLLBAR.'" type="text/javascript"></script>'.PHP_EOL;
				$jsContent .= '<script src="'.self::SCRIPT_URL_MESSAGE_BOX.'" type="text/javascript"></script>'.PHP_EOL;
				
				
				//common.js包含pcShare菜单定位
				if (!$includeHeadJs){
					$jsContent .= self::FEATURE_JS_HAIBAO_HEADER.PHP_EOL;
				}
			}
			
			//hb_common.css,头部导航栏、评论区要用
			if (	$iniModel->PcShare == FeatureIniModel::STATUS_ENABLE 
				|| 	stripos($html,'{{commentUrl}}') !== false
				||	stripos($html,'{{newCommentUrl}}')
			){
				$jsContent .= '<link rel="stylesheet" type="text/css" href="'.self::CSS_URL_HB_COMMON.'"/>'.PHP_EOL;
			}
			
			self::includeFeatureBottom($html, $iniModel,$isH5,$isChannel);
		}
		
		if ($isUpload){
			$jsContent = 'haibao.config.set("addPvUrl",'.self::formatJsValue(self::AJAX_URL_ADD_PV).');'.PHP_EOL.$jsContent;
			if (!$isH5){
				$jsContent = 'haibao.config.set("shareCountUrl",'.self::formatJsValue(self::AJAX_URL_SHARE_COUNT).');'.PHP_EOL.$jsContent;
			}
		
			$jsContent .= '<script src="'.self::SCRIPT_URL_HREF_RECORD.'" type="text/javascript"></script>'.PHP_EOL;
		}
	}
	
	private static function formatFeatureParamData($featureId,&$html,&$jsContent,&$htmlData,$isUpload = false,$dirPath = ''){
		$paramFilter = new FeatureParamFilter();
		$paramFilter->where(FeatureParamFilter::CONDITION_FIELD_NAME_FEATURE_ID,Condition::CONDITION_EQUAL,self::$featureDefineId);
		$cssData = array();
		if ($models = FeaturePublishBusiness::getAllParamList($paramFilter)){
			foreach ($models as $model){
				if ($model->ParamType == FeatureParamModel::PARAM_TYPE_JS){
					$jsContent = 'haibao.config.set("'.$model->Code.'",'.self::formatJsValue($model->Value).');'.PHP_EOL.$jsContent;
				}
				else if ($model->ParamType == FeatureParamModel::PARAM_TYPE_HTML){
					$htmlData[$model->Code] = $model->Value;
				}
				else if ($model->ParamType == FeatureParamModel::PARAM_TYPE_CSS){
					$cssData[$model->Code] = $model->Value;
				}
			}
		}

		//替换static地址
		$html = self::replaceStaticUrl($html,$isUpload);
		
		//评论url
		if (stripos($html,'{{commentUrl}}') !== false){
			if (!self::$feature){
				self::$feature = \haibao\cms\business\FeaturePublish::getFeatureById($featureId);
			}
			$commentUrl = 'http://comment.haibao.com/comment/comment/50/1236/'.$featureId.'/article/'.base64_encode(self::$feature->Url).'/';
			$html = str_replace('{{commentUrl}}',$commentUrl,$html);
			
			self::insertIntoHeaderBottom($html, '<script>document.domain = "haibao.com";</script>'.PHP_EOL);
			
			$jsContent .= '<script src="{{staticHost}}/js/checklogin,jquery.mask:{{version}}.js" type="text/javascript"></script>'.PHP_EOL;
		}
		
		if (stripos($html,'{{newCommentUrl}}') !== false){
			$commentUrl = 'http://comments.haibao.com/comments/'.$featureId.'/FEATURE/';
			$html = str_replace('{{newCommentUrl}}',$commentUrl,$html);
			
			self::insertIntoHeaderBottom($html, '<script>document.domain = "haibao.com";</script>'.PHP_EOL);
			
			$jsContent .= '<script src="{{staticHost}}/js/checklogin,jquery.mask:{{version}}.js" type="text/javascript"></script>'.PHP_EOL;
		}
		
		if ($htmlData){
			//html,替换{{$name}}标记
			$html = preg_replace_callback('/{{(.*?)}}/is',function ($matches) use ($htmlData) {
				if ($matches){
					$name = $matches[1];
					$replace = '';
					foreach ($htmlData as $key=>$value){
						if (strtolower($key) == strtolower($name)){
							$replace = nl2br($value);
						}
					}
		
					return $replace;
				}
			},$html);
		}
		
		$cssDir = $dirPath.DIRECTORY_SEPARATOR.'css'.DIRECTORY_SEPARATOR;
		if (file_exists($cssDir)){
			if (false !== ($dir = opendir($cssDir))){
				while(false !== ( $file = readdir($dir)) ) {
					if (( $file != '.' ) && ( $file != '..' )) {
						$realFileName = $cssDir.$file;
						$content = file_get_contents($realFileName);
						$content = self::replaceStaticUrl($content,$isUpload);
						$content = preg_replace_callback('/{{(.*?)}}/is',function ($matches) use ($cssData) {
							if ($matches){
								$name = $matches[1];
								$replace = '';
								foreach ($cssData as $key=>$value){
									if (strtolower($key) == strtolower($name)){
										$replace = nl2br($value);
									}
								}
	
								return $replace;
							}
						},$content);
						file_put_contents($realFileName,$content);
					}
				}
					
				closedir($dir);
			}
		}
	}
	
	private static function formateFeatureDynamicData(&$html){
		$pattern = '/{foreach (.*?)}(.*?){\/foreach}/is';
		$html = preg_replace_callback($pattern,'self::replaceDynamicData',$html);
	}
	
	private static function replaceDynamicData($matches){
		$str = $matches[0];
		$paramStr = $matches[1];
		$content = $matches[2];
		$param = self::newParseParameters($paramStr);
		
		if (!empty($param['dataSource'])){
			$str = '';
			$parameters = array(array(
					'code'=>$param['dataSource'],
					'currentPage'=>!empty($param['page']) ? intval($param['page']) : 1,
					'pageSize'=>!empty($param['pageSize']) ? intval($param['pageSize']) : 10,
					'order'=>!empty($param['order']) ? $param['order'] : 'createTime'
			));
			$result = \haibao\cms\business\FeaturePublish::getDynamicList(self::$featureDefineId, $parameters);
			try{
				if ($result && !empty($result[$param['dataSource']]['data'])){
					foreach ($result[$param['dataSource']]['data'] as $key=>$row){
						$replaceArr = array();
						$row['index'] = $key;
						foreach ($row as $name=>$value){
							$replaceArr['{'.$name.'}'] = $value;
						}
						
						self::$dynamicData = $row;
						$newContent = self::dealJudge($content);
						$str .= str_replace(array_keys($replaceArr),array_values($replaceArr),$newContent);
					}
				}
			}
			catch (\Exception $e){
				echo $e;
				exit;
			}
		}
		
		return $str;
	}
	
	private static function dealJudge($content){
		$pattern = '/\[(if|else if|elseif|else|\/if)(.*?)\]/is';
		$content = preg_replace_callback($pattern,'self::replaceJudge',$content);
		
		if (self::$dynamicJudgeMatched){
			$phpFileName = \haibao\cms\web\view\utility\Feature::getFeatureTmpPath().'/'.self::$featureId.'.php';
			$fileContent = '';
			foreach (self::$dynamicData as $key=>$value){
				$fileContent .= '<?php $'.$key.' = '.var_export($value,true).'; ?>'.PHP_EOL;
			}
			$fileContent .= $content;
			file_put_contents($phpFileName,$fileContent);
			ob_start();
			include($phpFileName);
			$content = ob_get_contents();
			ob_end_clean();
			//unlink($phpFileName);
		}
		
		return $content;
	}
	
	private static function replaceJudge($matches){
		self::$dynamicJudgeMatched = true;
		$allMatch = $matches[0];
		$judgeStr = $matches[1];
		$content = $matches[2];
		
		$str = '';
		if ($judgeStr == '/if'){
			$str = '<?php } ?>';
		}
		else{
			$str .= '<?php ';
			if ($judgeStr == 'elseif' || $judgeStr == 'else if' || $judgeStr == 'else'){
				$str .= ' } ';
			}
			$str .= $judgeStr;
			
			$replaceArr = array();
			foreach (self::$dynamicData as $key=>$value){
				$replaceArr['{'.$key.'}'] = '$'.$key;
			}
			$str .= str_replace(array_keys($replaceArr),array_values($replaceArr),$content).'{ ?>';
		}
		
		return $str;
	}
	
	private static function newParseParameters($content){
		$arr = array();
		$content = trim($content);
		$pattern = array(
				'/\s*\=\s*/',
				'/\s{2,}/',
		);
		$replacement = array(
				'=',
				' ',
		);
		$content = preg_replace($pattern, $replacement, $content);
		$params = explode(' ', $content);
		 
		for($i=0, $count=count($params); $i<$count; $i++){
			$param = explode('=', $params[$i]);
			if (count($param) == 2){
				$key = trim($param[0]);
				$value = trim($param[1], ' \'"');
				$arr[$key] = $value;
			}
		}
		 
		return $arr;
	}
	
	private static function formatFeature(&$html,$featureId,$oldFeatureId,$dirPath,$isH5,$isUpload,$isChannel){
		$jsContent = '</script>'.PHP_EOL;
		$htmlData = array();
		if (!self::$feature){
			self::$feature = \haibao\cms\business\FeaturePublish::getFeatureById($featureId);
			self::$featureDefineId = self::$feature->FeatureDefineId;
		}
		
		$htmlData['title'] = self::$feature->FeatureDefine->HtmlTitle;
		$htmlData['description'] = self::$feature->FeatureDefine->Description;
		$htmlData['keywords'] = self::$feature->FeatureDefine->Keywords;
		
		self::$featureId = $featureId;
		self::formatFeatureIniData($featureId,$html,$htmlData,$isUpload,$jsContent,$isH5,$isChannel);
		self::formatFeatureParamData($featureId,$html,$jsContent,$htmlData,$isUpload,$dirPath);
		self::formateFeatureDynamicData($html);
		
		//模板化html
		self::formatTemplateHtml($html,$featureId,$htmlData);
		
		$jsContent = 'haibao.config.set("featureId",'.self::formatJsValue($oldFeatureId).');'.PHP_EOL.$jsContent;
		$jsContent = '<script>'.PHP_EOL.$jsContent;
		
		$jsContent = self::replaceStaticUrl($jsContent,$isUpload);

		if ($isUpload){
			$html = str_replace(\haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN), \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DOMAIN),$html);
		}
		
		self::insertIntoHeaderBottom($html, $jsContent);
		
		//操作聚合记录
		$polymerInfoDataVal = array();
		$polymerInfoDataVal['Title'] = self::$feature->FeatureDefine->FeatureName;
		$polymerInfoDataVal['Summary'] = self::$feature->FeatureDefine->Description;
		$polymerInfoDataVal['PublishTime'] = self::$feature->PublishTime;
		$polymerInfoDataVal['ObjectType'] = \haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_FEATURE;
		if(self::$feature->IsH5){
			$polymerInfoDataVal['ObjectType'] = \haibao\cms\model\data\PolymerInfo::OBJECT_TYPE_H5;
		}
		$featureData = new \haibao\cms\data\FeaturePublish();
		$tagIds = $featureData->getTagIds($featureId);
		if(!empty($tagIds)){
			$tagIdList = \haibao\cms\business\Tag::loopGetParentTag($tagIds);
		
			$tagIdsStr = '';
			$tagIdsStrArr = array();
			if($tagIdList){
				$tagIdsStr = implode('|', array_values($tagIdList));
				$tagIdsStrArr = array_values($tagIdList);
			}
			$polymerInfoData = new \haibao\cms\data\PolymerInfo();
			$polymerInfoData->processPolymerInfoFeature($featureId,$polymerInfoDataVal,$tagIdsStr,$tagIdsStrArr);
		}
		
	}
	
	private static function formatTemplateHtml(&$html,$featureId,$htmlData){
		//获取动态数据
		if (
				($dynamicData = \haibao\cms\business\FeaturePublish::getAllDynamicListByFeatureId(self::$featureDefineId))
			||	$htmlData
		){
			$fileName = '/'.md5($featureId).'_'.mt_rand(1,1000).'.html';
			$templateFile = self::getFeatureTmpPath().$fileName;
			
			if (file_exists($templateFile)){
				unlink($templateFile);
			}
			if (!file_exists(self::getFeatureTmpPath())){
				mkdir(self::getFeatureTmpPath(),0777);
			}
			file_put_contents($templateFile, $html);
			
			$template = new \haibao\frame\http\Template();
			$config = new \stdClass();
			$config->templatePath = self::getFeatureTmpPath();
			$config->compilePath = self::getFeatureTmpPath();
			$config->cachePath = self::getFeatureTmpPath();
			$template->setConfig($config);
			
			foreach ($dynamicData as $key=>$value){
				$template->assign($key,$value);
			}
			
			foreach ($htmlData as $key=>$value){
				$template->assign($key,nl2br($value));
			}
			
			$html = $template->getHtml($fileName);
			
			unlink($templateFile);
			unlink($templateFile.'.php');
		}
	}
	
	private static function replaceStaticUrl($html,$isUpload){
		$staticReplaceUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_DOMAIN);
		if ($isUpload){
			$staticReplaceUrl = \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_CDN_DOMAIN);
		}
		$html = str_replace(
				array('{{staticHost}}','{{version}}'),
				array($staticReplaceUrl, \haibao\classlibrary\cms\Config::getConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_STATIC_VERSION)),
				$html
		);
		
		return $html;
	}
	
	private static function formatJsValue($value){
		if (intval($value) !== $value){
			//字符串
			$value = "'".addslashes($value)."'";
		}
	
		return $value;
	}
}